package com.mini.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mini.conditon.BussinessPageInfoCondition;
import com.mini.config.CheckLogin;
import com.mini.config.UnLoginException;
import com.mini.model.BusinessCompanyInfo;
import com.mini.model.BusinessXcxDic;
import com.mini.model.BussinessPageInfo;
import com.mini.req.BussinessPageInfoREQ;
import com.mini.service.*;
import com.mini.util.Md5Util;
import com.mini.vo.BusinessResult;
import com.mini.vo.CommonResultMessage;
import com.mini.vo.PageResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * xyf
 */
@RestController
@RequestMapping("/page")
@Api(tags = "页面接口")
@Slf4j
public class BussinessPageInfoController extends BaseController {

    @Autowired
    private BussinessPageInfoService bussinessPageInfoService;

    @Autowired
    private BusinessBaseService businessBaseService;

    @Autowired
    private BusinessXcxDicService businessXcxDicService;

    @Autowired
    private BusinessCompanyInfoService companyInfoService;

    private static final String H5_MODULE_PATH = "h5/module/";

    @Autowired
    private AliCDNService aliCDNService;

    @Autowired
    private TencentCDNService tencentCDNService;

    @Value("${mini.modular.index.url}")
    private String miniModularIndexUrl;

    @Value("${ali.test.states}")
    private String testStates;

    @Autowired
    private MiniAdminService miniAdminService;



    @CheckLogin
    @PostMapping("/pageList")
    @ApiOperation(value = "页面列表-分页", notes = "页面列表-分页")
    public BusinessResult<PageResultVO<BussinessPageInfo>> page(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                                 @RequestBody BussinessPageInfoCondition condition){
        PageResultVO<BussinessPageInfo> page = bussinessPageInfoService.page(condition,Authorization);
        List<BusinessXcxDic> templist = businessXcxDicService.getAll();
        Map<String,String> xcxmap = templist.stream().collect(Collectors.toMap(BusinessXcxDic::getXcxAppid, BusinessXcxDic::getAppName));
        for(BussinessPageInfo bussinessPageInfo : page.getRows()){
            if(StringUtils.isNotEmpty(bussinessPageInfo.getXcxAppid())){
                bussinessPageInfo.setXcxAppName(xcxmap.get(bussinessPageInfo.getXcxAppid()));
            }
        }
        return BusinessResult.createSuccessInstance(page);
    }

    @CheckLogin
    @ApiOperation(value = "创建页面", notes = "创建页面")
    @PostMapping(value = "/createPage")
    public BusinessResult<BussinessPageInfo> createPage(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                        @RequestBody BussinessPageInfoREQ req) {

        List<String> errMsgs = new ArrayList<>();
        if(req.getOcpmType() == null || (1!=req.getOcpmType().intValue() && 2!=req.getOcpmType().intValue() && 3!=req.getOcpmType().intValue() )){
            errMsgs.add("ocpmType值错误");
        }
        if(StringUtils.isBlank(req.getContent())){
            errMsgs.add("content值错误");
        }
        if(req.getUserId() == null || 0 == req.getUserId().intValue()){
            errMsgs.add("userId值错误");
        }
        if(StringUtils.isBlank(req.getVersion())){
            errMsgs.add("version值错误");
        }
        if(req.getStates() == null || (0 != req.getStates().intValue() && 1 != req.getStates().intValue())){
            errMsgs.add("states值错误");
        }
        if(errMsgs!= null && errMsgs.size()>0){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, JSON.toJSONString(errMsgs));
        }
        log.info("创建页面参数：{}", req.getDomainId()+","+req.getChannelCode()+","+req.getUserId() );

        String domain = "https://minih5.91lda.com/";
        String domain1 = "https://minih5.91lda.com";

        Long companyId = req.getDomainId();
        int domainType = 0;
        if(companyId != null && 0!= companyId.intValue()){
            BusinessCompanyInfo companyInfo = companyInfoService.findById(companyId);
            if(companyInfo != null){
                domain = "https://" + companyInfo.getDomain() + "/" ;
                domain1 = "https://" + companyInfo.getDomain()  ;
                domainType = companyInfo.getDomainType();
            }
            log.info("创建页面参数 companyInfo = {}, domain = {} domain1={} " , JSON.toJSONString(companyInfo) , domain,domain1);
        }

        log.info("创建页面参数  domain = {} domain1={}" , domain ,domain1);
        //上传oss生成js地址
        BussinessPageInfo bussinessPageInfo = new BussinessPageInfo();
        BeanUtils.copyProperties(req,bussinessPageInfo);
        bussinessPageInfo.setUpdateUser(req.getUserId());
        bussinessPageInfo.setCreateUser(req.getUserId());
        bussinessPageInfo.setFzId(req.getUserId());
        if(req.getPageType() != null && req.getPageType()==2){//小程序模版，用域名做小程序路径
            bussinessPageInfo.setUrl(req.getUrl());
        }else {
            String h5url = connectRequestUrl(req.getVersion(), domain);
            bussinessPageInfo.setUrl(h5url);
        }
        if(bussinessPageInfo.getId() > 0){
            BussinessPageInfo temp = bussinessPageInfoService.findById(bussinessPageInfo.getId());
            Long id = bussinessPageInfo.getId();
            String pageId = "CTYM" + id;
            String jsuuid =  Md5Util.getMd516Str(pageId);
            bussinessPageInfo.setJsUuid(jsuuid);
            if(req.getPageType() != null && req.getPageType()==2) {//小程序模版，用域名做小程序路径

            }else{

                if (bussinessPageInfo.getStates() != null && 1 == bussinessPageInfo.getStates().intValue()) {
                    String jsUrl = uploadPageJs2Oss(bussinessPageInfo.getContent(), jsuuid,domainType,domain1);
                    bussinessPageInfo.setJsUrl(jsUrl);
                    //预热
                    if(domainType == 0){//阿里

                        aliCDNService.refreshCaches(jsUrl);
                    }else {
                        tencentCDNService.refreshCaches(jsUrl);
                    }
                }
            }
            bussinessPageInfo.setCreateTime(temp.getCreateTime());
            bussinessPageInfo.setUpdateTime(new Date());
            bussinessPageInfo.setFzId(temp.getFzId());
            bussinessPageInfo.setCreateUser(temp.getCreateUser());
            bussinessPageInfoService.save(bussinessPageInfo);
        }else {
            bussinessPageInfo.setUpdateTime(new Date());
            bussinessPageInfo.setCreateTime(new Date());
            bussinessPageInfo = bussinessPageInfoService.save(bussinessPageInfo);
            Long id = bussinessPageInfo.getId();
            String pageId = "CTYM" + id;
            String jsuuid =  Md5Util.getMd516Str(pageId);
            bussinessPageInfo.setJsUuid(jsuuid);
            if(req.getPageType() != null && req.getPageType()==2) {//小程序模版，用域名做小程序路径

            }else{

                if (bussinessPageInfo.getStates() != null && 1 == bussinessPageInfo.getStates().intValue()) {
                    String jsUrl = uploadPageJs2Oss(bussinessPageInfo.getContent(), jsuuid,domainType,domain1);
                    bussinessPageInfo.setJsUrl(jsUrl);
                    //预热
                    if(domainType == 0){//阿里

                        aliCDNService.refreshCaches(jsUrl);
                    }else {
                        tencentCDNService.refreshCaches(jsUrl);
                    }
                }
            }
            bussinessPageInfoService.save(bussinessPageInfo);
        }

        return  BusinessResult.createSuccessInstance(bussinessPageInfo);
    }



    @CheckLogin
    @ApiOperation(value = "查询页面名称是否合法", notes = "查询页面名称是否合法 pageok=1 名字合法 ")
    @PostMapping(value = "/pageNameOk")
    public BusinessResult< Map<String,Object>> pageNameOk(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                                          @ApiParam(value = "页面名称",required = true) @RequestParam String pageName ) {

        Map<String,Object> flagmap = new HashMap<>();
        List<BussinessPageInfo> relist = bussinessPageInfoService.findPageNameOk(pageName);
        int flag = 1;
        if(relist != null && relist.size()>0){
            flag = 0;
        }
        flagmap.put("pageok",flag);

        return  BusinessResult.createSuccessInstance(flagmap);
    }




    @CheckLogin
    @GetMapping("/del")
    @ApiOperation(value = "删除页面", notes = "删除页面")
    public BusinessResult del(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                              @ApiParam(value = "操作人id",required = true)@RequestParam Long userId,
                              @ApiParam(value = "页面id",required = true)@RequestParam Long pageId){
        if(userId == null || 0 == userId.intValue()){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR,"用户错误");
        }

        if(pageId == null || 0 == pageId.intValue()){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR,"页面id错误");
        }

        BussinessPageInfo bussinessPageInfo = bussinessPageInfoService.findById(pageId);
        if(bussinessPageInfo != null ){
            Integer states = bussinessPageInfo.getStates();
            if( states != null && 0 == states.intValue() ){
                bussinessPageInfoService.delete(bussinessPageInfo);
                return BusinessResult.createSuccessInstance("删除成功");
            }else {
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR,"非草稿状态，不能删除");
            }
        }
        return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR,"数据不存在");
    }

    @CheckLogin
    @ApiOperation(value = "站点建站图片", notes = "站点建站图片")
    @PostMapping(value = "/uploadImg")
    public BusinessResult<String> uploadImg(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                            @ApiParam(value = "图片文件",required = true)@RequestParam("file") MultipartFile file
                                            ) {

        String pageId="CTYM";
        String path = H5_MODULE_PATH + pageId + "/img/" ;
        String imgUrl = tencentUploadService.uploadImg(file,  path);
        return BusinessResult.createSuccessInstance(imgUrl);
    }

    public String uploadPageJs2Oss(String content,String pageId,int type,String domain){
        String uploadSuccessUrl = "";
        String path = H5_MODULE_PATH  + pageId + "/file/" + pageId + ".js";
        if(type == 0){//阿里云
            uploadSuccessUrl = ossService.uploadContent2OSS(content, path,domain);
        }else {
            uploadSuccessUrl = tencentUploadService.uploadContent2OSS(content, path,domain);
        }

        return uploadSuccessUrl;
    }



    protected String connectRequestUrl(
                                       String version,
                                       String domain){
        StringBuilder sb = new StringBuilder();
        sb.append(domain);
        if("test".equalsIgnoreCase(testStates)){
            sb.append("test/");
        }
        sb.append(H5_MODULE_PATH);
        if(!("1".equalsIgnoreCase(version))){
            sb.append(version).append("/");
        }
        sb.append("index.html");

        return sb.toString();
    }

    @CheckLogin
    @GetMapping("/todayNewPageList")
    @ApiOperation(value = "今天新修改的页面列表", notes = "今天新修改的页面列表")
    public BusinessResult<PageResultVO<BussinessPageInfo>> todayNewPageList(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization
    ){
        BussinessPageInfoCondition condition = new BussinessPageInfoCondition();
        Long loginUserId = this.miniAdminService.getLoginUserId(Authorization);
        if(loginUserId == null){
            throw new UnLoginException("未登录！");
        }else {
            condition.setUserId(loginUserId);
        }
        List<BussinessPageInfo> page = bussinessPageInfoService.todayNewPage(condition);
        return BusinessResult.createSuccessInstance(page);
    }



}

